//
//	 ______    ______    ______    
//	/\  __ \  /\  ___\  /\  ___\   
//	\ \  __<  \ \  __\_ \ \  __\_ 
//	 \ \_____\ \ \_____\ \ \_____\ 
//	  \/_____/  \/_____/  \/_____/ 
//
//	Powered by BeeFramework
//
//
//  MainNearBy_Board.m
//  DingDing
//
//  Created by LHL on 14/11/25.
//  Copyright (c) 2014年 com.gordon. All rights reserved.
//

#import "MainNearBy_Board.h"
#import "PullLoader.h"
#import "FootLoader.h"
#import "NearByCell.h"
#import "AddPetCell.h"
#import "PersonalHomePage.h"
#import "AddPet.h"
#import "dynamicsVC.h"
#import "ChatListViewController.h"
#import "Board_iPhone_Login.h"
#import "AFNetworking.h"
#import "LargeImageViewController.h"
#pragma mark -

//两次提示的默认间隔
static const CGFloat kDefaultPlaySoundInterval = 3.0;
@interface MainNearBy_Board()<IChatManagerDelegate>
{
	//<#@private var#>
    ChatListViewController *_chatListVC;
}
@property (strong, nonatomic) NSDate *lastPlaySoundDate;
@end


@implementation MainNearBy_Board

SUPPORT_AUTOMATIC_LAYOUT( YES )
SUPPORT_RESOURCE_LOADING( YES )
DEF_OUTLET(BeeUIScrollView, list)
DEF_MODEL(getNearbyUser, igetNearbyUser)
//DEF_MODEL(getPetList, igetPetList)

- (void)load
{
    self.igetNearbyUser = [getNearbyUser modelWithObserver:self];
}

- (void)unload
{
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
    return YES;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
    return YES;
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldBeRequiredToFailByGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return [gestureRecognizer isKindOfClass:UIScreenEdgePanGestureRecognizer.class];
}

#pragma mark - Signal

ON_CREATE_VIEWS( signal )
{
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(relogin) name:@"loginsuccess" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(guideSuccess) name:@"guide" object:nil];
    self.navigationBarShown = YES;
    self.navigationBarTitle=@"附近";
    NSDictionary *dic = [NSDictionary dictionaryWithObject:[UIColor whiteColor] forKey:NSForegroundColorAttributeName];
    self.navigationController.navigationBar.titleTextAttributes = dic;
    self.navigationBarLeft = [UIImage imageNamed:@"trends.png"];

    self.navigationBarRight = [UIImage imageNamed:@"message01.png"];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(presentLoginPage) name:@"logout" object:nil];
    
    //获取未读消息数，此时并没有把self注册为SDK的delegate，读取出的未读数是上次退出程序时的
    self.view.backgroundColor= [UIColor whiteColor];
    [self registerNotifications];
    self.list.headerClass = [PullLoader class];
    self.list.headerShown = YES;
    
    self.list.footerClass = [FootLoader class];
    self.list.footerShown = YES;
    self.list.lineCount = 1;
    self.list.whenReloading=^{
        NSInteger datacount = 1;
        if (self.igetNearbyUser.data.count == 0) {
            return ;
        }else{
            for (int i = 0; i < self.igetNearbyUser.data.count; i++) {
                NEARBYMODEL *model = self.igetNearbyUser.data[i];
                //去掉服务器返回的错误数据
                if (model.user_id == nil || [[NSUserDefaults standardUserDefaults]objectForKey:@"user_id" ] ==model.user_id) {
                    [self.igetNearbyUser.data removeObjectAtIndex:i];
                    continue;
                }
                if (![model.user_id isEqualToString:[[NSUserDefaults standardUserDefaults]objectForKey:@"user_id" ]]) {
                    datacount++;
                }
            }
        }
        self.list.total = datacount;
        for (BeeUIScrollItem *item in self.list.items) {
            if (self.list.total == 0) {
                return ;
            }
            item.clazz = [NearByCell class];
            item.size = CGSizeMake([UIScreen mainScreen].bounds.size.width, 100);
            item.view.backgroundColor = [UIColor greenColor];
            if (item.index == 0) {
                NEARBYMODEL *model = [[NEARBYMODEL alloc]init];
                model.user_id = [[NSUserDefaults standardUserDefaults]objectForKey:@"user_id"];
                model.petname = [[NSUserDefaults standardUserDefaults]objectForKey:@"petname"];
                model.gender = [[NSUserDefaults standardUserDefaults]objectForKey:@"gender"];
                model.signature = [[NSUserDefaults standardUserDefaults]objectForKey:@"signature"];
                model.imgurl = [[NSUserDefaults standardUserDefaults]objectForKey:@"imgurl"];
                model.address = [[NSUserDefaults standardUserDefaults]objectForKey:@"address"];
//                model.pet_id = [[NSUserDefaults standardUserDefaults]objectForKey:@"pet_id"];
                model.distance = @"0.0";
                item.data = model;
            }else{
                item.data = self.igetNearbyUser.data[item.index-1];
            }
        }
    };
    if ([[NSUserDefaults standardUserDefaults]boolForKey:@"guide"] == YES) {
        [self initViewFunc];
    }
    self.list.footerLoading = YES;
    self.list.whenHeaderRefresh=^{
         [self.igetNearbyUser firstPage];
    };
    self.list.whenFooterRefresh=^{
       [self.igetNearbyUser nextPage];
    };
    [self setupUnreadMessageCount];
}

//引导页完成后调用
-(void)guideSuccess{
    [self initViewFunc];
}

-(void)initViewFunc{
    NSString *logout = [[NSUserDefaults standardUserDefaults]objectForKey:@"logout"];
    NSString *isadd = [[NSUserDefaults standardUserDefaults]objectForKey:@"isaddpet"];
    
    NSLog(@"%@---%@",logout,isadd);
    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"logout"] isEqualToString:@"1"] ||[[[NSUserDefaults standardUserDefaults]objectForKey:@"logout"] isEqualToString:@""] || [[NSUserDefaults standardUserDefaults]objectForKey:@"logout"] ==nil  ) {
        Board_iPhone_Login *board = [[Board_iPhone_Login alloc]init];
        UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:board];
        [self.navigationController presentViewController:nav animated:YES completion:nil];
        return;
    }
    
    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"isaddpet"] isEqualToString:@"0"] || [[[NSUserDefaults standardUserDefaults]objectForKey:@"isaddpet"] isEqualToString:@""] || [[NSUserDefaults standardUserDefaults]objectForKey:@"isaddpet"]==nil) {
        AddPet *board = [[AddPet alloc]init];
        UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:board];
        [self.navigationController presentViewController:nav animated:YES completion:nil];
        return;
    }
    [self loginSuccessful];
    [self.igetNearbyUser firstPage];
}

//登录后调用
-(void)relogin{
    [self loginSuccessful];
    [self.igetNearbyUser firstPage];
    self.list.footerLoading = YES;
    [self setupUnreadMessageCount];
}

//显示登录界面
-(void)presentLoginPage{
    Board_iPhone_Login *board = [[Board_iPhone_Login alloc]init];
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:board];
    [self.navigationController presentViewController:nav animated:YES completion:nil];
}

//本地登录成功后调用登录环信聊天及上传坐标
-(void)loginSuccessful{

    NSString *lat = [[NSUserDefaults standardUserDefaults] objectForKey:@"lat"];
    if (lat != nil) {
        AFHTTPRequestOperation * op = [[AFHTTPRequestOperation alloc]initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.dddd.gg/index.php/pet/updateUserPlace?user_id=%@&lat=%@&lng=%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"user_id"],[[NSUserDefaults standardUserDefaults] objectForKey:@"lat"],[[NSUserDefaults standardUserDefaults] objectForKey:@"lnt"]]]]];
        
        [op start];
        [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject){
            NSDictionary *tt = [NSJSONSerialization JSONObjectWithData:[operation responseData] options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"update location success ---%@",tt);
        }failure:^(AFHTTPRequestOperation *operation, NSError *error){
            NSLog(@"update location error is %@",error);
        }];
    }
    [[EaseMob sharedInstance].chatManager asyncLoginWithUsername:[[NSUserDefaults standardUserDefaults] objectForKey:@"im_username"] password:[[NSUserDefaults standardUserDefaults]objectForKey:@"im_password"]  completion:
     ^(NSDictionary *loginInfo, EMError *error) {
         if (loginInfo && !error) {
             [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@YES];
             EMPushNotificationOptions *option = [[EMPushNotificationOptions alloc]init];
             option.displayStyle = ePushNotificationDisplayStyle_simpleBanner;
                 [[EaseMob sharedInstance].chatManager setNickname:[[NSUserDefaults standardUserDefaults] objectForKey:@"petname"]];
             [[EaseMob sharedInstance].chatManager asyncUpdatePushOptions:option];
         }else {
             switch (error.errorCode) {
                 case EMErrorServerNotReachable:
                     TTAlertNoTitle(@"连接服务器失败!");
                     break;
                 case EMErrorServerAuthenticationFailure:
                     TTAlertNoTitle(@"用户名或密码错误");
                     break;
                 case EMErrorServerTimeout:
                     TTAlertNoTitle(@"连接服务器超时!");
                     break;
                 default:
                     TTAlertNoTitle(@"登录失败");
                     break;
             }
         }
     } onQueue:nil];
}

ON_DELETE_VIEWS( signal )
{
    
}

ON_LAYOUT_VIEWS( signal )
{
}

ON_WILL_APPEAR( signal )
{
    self.navigationBarShown = YES;
    [self setupUnreadMessageCount];
}

ON_DID_APPEAR( signal )
{
}

ON_WILL_DISAPPEAR( signal )
{
    
}

ON_DID_DISAPPEAR( signal )
{
}

ON_SIGNAL3( BeeUINavigationBar, LEFT_TOUCHED, signal )
{
    UIStoryboard *st = [UIStoryboard storyboardWithName:@"PersonalHome" bundle:nil];
    dynamicsVC *vc = [st instantiateViewControllerWithIdentifier:@"dynamicsVC"];
    [self.navigationController pushViewController:vc animated:YES];
}

ON_SIGNAL3( BeeUINavigationBar, RIGHT_TOUCHED, signal )
{
    ChatListViewController *chat = [[ChatListViewController alloc]initWithNibName:nil bundle:nil];
    chat.nearbyUsers = self.igetNearbyUser.data;
    [self.navigationController pushViewController:chat animated:YES];
}

#pragma mark - private

-(void)registerNotifications
{
    [self unregisterNotifications];
    
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
}

-(void)unregisterNotifications
{
    [[EaseMob sharedInstance].chatManager removeDelegate:self];
}

- (BOOL)needShowNotification:(NSString *)fromChatter
{
    BOOL ret = YES;
    NSArray *igGroupIds = [[EaseMob sharedInstance].chatManager ignoredGroupList];
    for (NSString *str in igGroupIds) {
        if ([str isEqualToString:fromChatter]) {
            ret = NO;
            break;
        }
    }
    
    if (ret) {
        EMPushNotificationOptions *options = [[EaseMob sharedInstance].chatManager pushNotificationOptions];
        
        do {
            if (options.noDisturbing) {
                NSDate *now = [NSDate date];
                NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitHour | NSCalendarUnitMinute
                                                                               fromDate:now];
                
                NSInteger hour = [components hour];
                //        NSInteger minute= [components minute];
                
                NSUInteger startH = options.noDisturbingStartH;
                NSUInteger endH = options.noDisturbingEndH;
                if (startH>endH) {
                    endH += 24;
                }
                
                if (hour>=startH && hour<=endH) {
                    ret = NO;
                    break;
                }
            }
        } while (0);
    }
    
    return ret;
}

// 收到消息回调
-(void)didReceiveMessage:(EMMessage *)message
{
    BOOL needShowNotification = message.isGroup ? [self needShowNotification:message.conversation.chatter] : YES;
    if (needShowNotification) {
#if !TARGET_IPHONE_SIMULATOR
        [self playSoundAndVibration];
        
        BOOL isAppActivity = [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive;
        if (!isAppActivity) {
            [self showNotificationWithMessage:message];
        }
#endif
    }
}

- (void)playSoundAndVibration{
    NSTimeInterval timeInterval = [[NSDate date]
                                   timeIntervalSinceDate:self.lastPlaySoundDate];
    if (timeInterval < kDefaultPlaySoundInterval) {
        //如果距离上次响铃和震动时间太短, 则跳过响铃
        NSLog(@"skip ringing & vibration %@, %@", [NSDate date], self.lastPlaySoundDate);
        return;
    }
    
    //保存最后一次响铃时间
    self.lastPlaySoundDate = [NSDate date];
    
    // 收到消息时，播放音频
    [[EaseMob sharedInstance].deviceManager asyncPlayNewMessageSound];
    // 收到消息时，震动
    [[EaseMob sharedInstance].deviceManager asyncPlayVibration];
}


#pragma mark - IChatManagerDelegate 登陆回调（主要用于监听自动登录是否成功）

- (void)didLoginWithInfo:(NSDictionary *)loginInfo error:(EMError *)error
{
    if (error) {
        NSString *hintText = @"你的账号登录失败，正在重试中... \n点击 '登出' 按钮跳转到登录页面 \n点击 '继续等待' 按钮等待重连成功";
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:hintText
                                                           delegate:self
                                                  cancelButtonTitle:@"继续等待"
                                                  otherButtonTitles:@"登出",
                                  nil];
        alertView.tag = 99;
        [alertView show];
        [_chatListVC isConnect:NO];
    }
}

- (void)didLoginFromOtherDevice
{
    [[EaseMob sharedInstance].chatManager asyncLogoffWithCompletion:^(NSDictionary *info, EMError *error) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:@"你的账号已在其他地方登录"
                                                           delegate:self
                                                  cancelButtonTitle:@"确定"
                                                  otherButtonTitles:nil,
                                  nil];
        alertView.tag = 100;
        [Common cleanUserInfo];
        [alertView show];
    } onQueue:nil];
}

- (void)didRemovedFromServer {
    [[EaseMob sharedInstance].chatManager asyncLogoffWithCompletion:^(NSDictionary *info, EMError *error) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:@"你的账号已被从服务器端移除"
                                                           delegate:self
                                                  cancelButtonTitle:@"确定"
                                                  otherButtonTitles:nil,
                                  nil];
        alertView.tag = 101;
        [alertView show];
    } onQueue:nil];
}


#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 99) {
        if (buttonIndex != [alertView cancelButtonIndex]) {
            [[EaseMob sharedInstance].chatManager asyncLogoffWithCompletion:^(NSDictionary *info, EMError *error) {
//                [[ApplyViewController shareController] clear];
                [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
            } onQueue:nil];
        }
    }
    else if (alertView.tag == 100) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"logout" object:nil];
        [self.navigationController popToRootViewControllerAnimated:YES];
    } else if (alertView.tag == 101) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
    }
}


// 未读消息数量变化回调
-(void)didUnreadMessagesCountChanged
{
    [self setupUnreadMessageCount];
}

- (void)didFinishedReceiveOfflineMessages:(NSArray *)offlineMessages{
    [self setupUnreadMessageCount];
}

// 统计未读消息数
-(void)setupUnreadMessageCount
{
    NSArray *conversations = [[[EaseMob sharedInstance] chatManager] conversations];
    NSInteger unreadCount = 0;
    for (EMConversation *conversation in conversations) {
        unreadCount += conversation.unreadMessagesCount;
    }
    if (unreadCount >0 ) {
        self.navigationBarRight = [UIImage imageNamed:@"message02.png"];
    }else{
        self.navigationBarRight = [UIImage imageNamed:@"message01.png"];
    }
}

- (void)showNotificationWithMessage:(EMMessage *)message
{
    EMPushNotificationOptions *options = [[EaseMob sharedInstance].chatManager pushNotificationOptions];
    //发送本地推送
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    notification.fireDate = [NSDate date]; //触发通知的时间
    
    if (options.displayStyle == ePushNotificationDisplayStyle_messageSummary) {
        id<IEMMessageBody> messageBody = [message.messageBodies firstObject];
        NSString *messageStr = nil;
        switch (messageBody.messageBodyType) {
            case eMessageBodyType_Text:
            {
                messageStr = ((EMTextMessageBody *)messageBody).text;
            }
                break;
            case eMessageBodyType_Image:
            {
                messageStr = @"[图片]";
            }
                break;
            case eMessageBodyType_Location:
            {
                messageStr = @"[位置]";
            }
                break;
            case eMessageBodyType_Voice:
            {
                messageStr = @"[音频]";
            }
                break;
            case eMessageBodyType_Video:{
                messageStr = @"[视频]";
            }
                break;
            default:
                break;
        }
        
        NSString *title = message.from;
        if (message.isGroup) {
            NSArray *groupArray = [[EaseMob sharedInstance].chatManager groupList];
            for (EMGroup *group in groupArray) {
                if ([group.groupId isEqualToString:message.conversation.chatter]) {
                    title = [NSString stringWithFormat:@"%@(%@)", message.groupSenderName, group.groupSubject];
                    break;
                }
            }
        }
        
        notification.alertBody = [NSString stringWithFormat:@"%@:%@", title, messageStr];
    }
    else{
        notification.alertBody = @"您有一条新消息";
    }
    
#warning 去掉注释会显示[本地]开头, 方便在开发中区分是否为本地推送
//    notification.alertBody = [[NSString alloc] initWithFormat:@"[本地]%@", notification.alertBody];
    
    notification.alertAction = @"打开";
    notification.timeZone = [NSTimeZone defaultTimeZone];
    //发送通知
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
    //    UIApplication *application = [UIApplication sharedApplication];
    //    application.applicationIconBadgeNumber += 1;
}



ON_SIGNAL3(getNearbyUser, RELOADED, SIGNAL){
    self.list.headerLoading=NO;
    self.list.footerLoading=NO;
    if ([self.igetNearbyUser.code isEqualToString:@"200"]) {
        [self.list reloadData];
        self.list.footerMore = self.igetNearbyUser.more;
    }else{
        [self presentMessageTips:self.igetNearbyUser.message];
        self.list.footerMore = self.igetNearbyUser.more;
    }
}

ON_SIGNAL3(getNearbyUser, RELOADING, SIGNAL){
    if (self.list.HEADER_REFRESH) {
        self.list.headerLoading=YES;
    }else{
        self.list.footerLoading=YES;
    }
}

ON_SIGNAL3(getNearbyUser, FAILED, SIGNAL){
    self.list.headerLoading=NO;
    self.list.footerLoading=NO;
    [self presentMessageTips:self.igetNearbyUser.message];
}

ON_SIGNAL3(NearByCell, mask, SIGNAL){
    NearByCell* cell = (NearByCell *)SIGNAL.sourceCell;
    NEARBYMODEL *model = cell.data;
//    NSInteger index = [self.igetNearbyUser.data indexOfObject:model];
    if ([model.user_id isEqualToString:[[NSUserDefaults standardUserDefaults]objectForKey:@"user_id"]]) {
        if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"isaddpet"] isEqualToString:@"0"]) {
            AddPet *add = [[AddPet alloc]init];
            [self.navigationController pushViewController:add animated:YES];
        }else{
            UIStoryboard *story = [UIStoryboard storyboardWithName:@"PersonalHome" bundle:nil];
            PersonalHomePage *vc = [story instantiateViewControllerWithIdentifier:@"personalVC"];
            NEARBYMODEL *specmodel = [[NEARBYMODEL alloc]init];
            specmodel.user_id = [[NSUserDefaults standardUserDefaults]objectForKey:@"user_id"];
            vc.nearbymodel = specmodel;
            [self.navigationController pushViewController:vc animated:YES];
        }
        
    }else{
        UIStoryboard *story = [UIStoryboard storyboardWithName:@"PersonalHome" bundle:nil];
        PersonalHomePage *vc = [story instantiateViewControllerWithIdentifier:@"personalVC"];
        vc.nearbymodel = model;
        [self.navigationController pushViewController:vc animated:YES];
    }
    
    

    
}

@end
